//
// Created by liz on 24-12-6.
//

#include "QRcode.h"
#include "bsp_usart.h"
#include "memory.h"
#include "stdlib.h"
#include "string.h"

#define QRCODEBUFFERLENGTH 64

uint8_t QRCodeBuffer[QRCODEBUFFERLENGTH];

QRCodeInstance *QRinstance ;

static void DecodeQR(USARTInstance *_handle);

QRCodeInstance *QRCode_Init(QRCode_Init_Config_s *QRCode_config){
    QRinstance = (QRCodeInstance *)malloc(sizeof(QRCodeInstance));
    memset(QRinstance, 0, sizeof(QRCodeInstance));

    USART_Init_Config_s usart_config={.usart_handle = QRCode_config->usart_handle,
    .module_callback = DecodeQR,
    .recv_buff_size = QRCODEBUFFERLENGTH,
    .duplex_mode = USART_DUPLEX_FULL,
    .tx_fifo_mode = USART_FIFO_DISABLE
    };
    QRinstance->usart_instance = USARTRegister(&usart_config);

    QRinstance->receive_message=QRCodeBuffer;
    QRinstance->scancount=0;

    return QRinstance;
}

uint8_t *QRCode_ReadBuffer(QRCodeInstance *_instance) {
    QRinstance->readable=0;
    return _instance->receive_message;

}

void QRCode_ScanRequest(QRCodeInstance *_instance)
{
    static uint8_t ScanRequestBuffer[]={0x7E,0x00,0x08,0x01,0x00,0x02,0x01,0xAB,0xCD};
    USARTSend(_instance->usart_instance,ScanRequestBuffer,sizeof(ScanRequestBuffer),USART_TRANSFER_BLOCKING);
}

void DecodeQR(USARTInstance *_handle) {
    memcpy(QRCodeBuffer,_handle->recv_buff,strlen(_handle->recv_buff));
    memset(_handle->recv_buff,0,strlen(_handle->recv_buff));
    QRinstance->scancount++;
    QRinstance->readable=1;
}



